package com.ts.proj.controller;

import com.alibaba.fastjson.JSONArray;
import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.SystemConstantEntity;
import com.ts.proj.entity.SystemMenuEntity;
import com.ts.proj.entity.SystemRoleEntity;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.service.SystemConstantService;
import com.ts.proj.service.SystemMenuService;
import com.ts.proj.service.SystemRoleService;
import com.ts.proj.service.SystemUserService;
import com.ts.util.JsonUtils;
import com.ts.util.JurisdictionUtil;
import com.ts.util.PageData;
import com.ts.util.RightsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class SystemUserController extends BaseController {

    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private SystemUserService systemUserService;

    @Autowired
    private SystemConstantService systemConstantService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemMenuService systemMenuService;

    /**
     * 用户管理--用户列表
     * @return
     */
    @RequestMapping("/admin-list-manage")
    public ModelAndView adminListManage(){
        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){
            Object attribute = this.getRequest().getSession().getAttribute(ConsoleConstant.BTNRIGHTS);
            List<PageData> buttonList = (List<PageData>) JSONArray.parse(attribute.toString());
            modelAndView.addObject("buttons", buttonList);
            viewName = "admin/admin-list-manage";
        }
        modelAndView.setViewName(viewName);
        return modelAndView;
    }

    @RequestMapping("/admin-add")
    public ModelAndView adminAddManage() {
        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){

            PageData pd = this.getPageData();
            List<PageData> roleList = new ArrayList<>();
            List<PageData> groupList = new ArrayList<>();
            List<PageData> levelList = new ArrayList<>();
            //先读取redis
            try{
                String role = stringRedisTemplate.opsForValue().get("role");
                String group = stringRedisTemplate.opsForValue().get("group");
                String powerLevel = stringRedisTemplate.opsForValue().get("level");
                roleList = JsonUtils.jsonToObject(role, List.class);
                groupList = JsonUtils.jsonToObject(group, List.class);
                levelList = JsonUtils.jsonToObject(powerLevel, List.class);
                //表示如果不存在
                if(null==role){
                    roleList = getRole();
                    stringRedisTemplate.opsForValue().set("role", JsonUtils.objectToJson(roleList));
                }
                if(null==group){
                    groupList = getConstantByParam("group-types");
                    stringRedisTemplate.opsForValue().set("group-types", JsonUtils.objectToJson(groupList));
                }
                if(null==powerLevel){
                    levelList = getConstantByParam("power-level-types");
                    stringRedisTemplate.opsForValue().set("power-level-types", JsonUtils.objectToJson(levelList));
                }
            }catch (Exception e){
                //表示如果连不上
                roleList = getRole();
                groupList = getConstantByParam("group-types");
                levelList = getConstantByParam("power-level-types");
            }
            SystemUserEntity id = new SystemUserEntity();
            if(null!=pd.get("id")&&!"".equals(pd.getString("id"))){
                id = systemUserService.findById(Integer.valueOf(pd.getString("id")));
            }
            modelAndView.addObject("user", id);
            modelAndView.addObject("role_list", roleList);
            modelAndView.addObject("group_list", groupList);
            modelAndView.addObject("level_list", levelList);
            viewName = "admin/admin-add";
        }
        modelAndView.setViewName(viewName);
        return modelAndView;
    }

    @RequestMapping("/user-set")
    public ModelAndView userSet(){

        ModelAndView modelAndView = this.getModelAndView();
        String viewName = "login";
        if(JurisdictionUtil.isValid()){

            HttpSession session = this.getRequest().getSession();
            //将用户存入session
            SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
            String rights = session.getAttribute(ConsoleConstant.RIGHTS).toString();
            String checkBoxRights = "SS" ;
            PageData result = new PageData();
            PageData pageData = new PageData();
            pageData.put("userId", user.getId());
            result.put("short", user.getUserShortCut());
            checkBoxRights = (user.getUserShortCut() == null || user.getUserShortCut().equals("")) ? "SS" : user.getUserShortCut();
            modelAndView.addObject("user", user);
            modelAndView.addObject("shortInfo", shortList(rights,checkBoxRights.substring(1)));
            viewName = "admin/user-set";
        }
        modelAndView.setViewName(viewName);
        return modelAndView;

    }

    //获取角色
    private List<PageData> getRole(){
        PageData p = new PageData();
        p.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<SystemRoleEntity> all = systemRoleService.findAll(p);
        List<PageData> list = new ArrayList<>();
        for(SystemRoleEntity systemRoleEntity : all){
            PageData pd = new PageData();
            pd.put("key", systemRoleEntity.getId()) ;
            pd.put("value", systemRoleEntity.getRoleName());

            list.add(pd);
        }
        return list;
    }
    //获取组别
    private List<PageData> getConstantByParam(String key){
        List<PageData> list = new ArrayList<>();
        PageData param = new PageData();
        param.put("constantKey", key);
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<SystemConstantEntity> all = systemConstantService.findAll(param);
        for(SystemConstantEntity systemConstantEntity :all){
            PageData pd = new PageData();
            pd.put("key", systemConstantEntity.getConstantValue());
            pd.put("value", systemConstantEntity.getConstantValueDesc());
            list.add(pd);
        }
        return list;
    }

    //--------------------------------------------------------------------------//
    private List<PageData> shortList (String rights, String shortCuts){
        List<Integer> idsList = new ArrayList<>();
        List<PageData> resultList = new ArrayList<>();
        for(int i=0;i<200;i++){
            if (RightsHelper.testRights(rights.substring(1), i)) {
                idsList.add(i);
            }
        }
        Integer[] idsArray = new Integer[idsList.size()];
        idsList.toArray(idsArray);
        List<SystemMenuEntity> allById = systemMenuService.findAllById(idsArray);
        for(SystemMenuEntity menu : allById){
            if(menu.getParentId().equals("0")){
                continue;
            }
            PageData pageData = new PageData();
            pageData.put("menuId", menu.getId());
            pageData.put("menuName", menu.getMenuName());
            pageData.put("checkBoxName", "checkBoxName_" + menu.getId());
            String str = "unchecked";
            try {
                if(RightsHelper.testRights(shortCuts,menu.getId())){
                    str = "checked";
                }
            } catch (NumberFormatException e) {

            }

            pageData.put("check", str);
            resultList.add(pageData);
        }
        return resultList;
    }
}
